package com.wontube.core.srv.time;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wontube.core.srv.ServiceConstants;

/**
 * 
 * @author yuechao
 * 
 *         本地事件服务。总是取本地时间，并广播给监听者
 * 
 */
public class LocalTimeService implements ITimeService {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	// 监听者列表
	private ArrayList<ITimeListener> list = new ArrayList<ITimeListener>();

	// 定时器
	private Timer timer;

	// 定时任务
	private TheTimerTask task;

	// 定时广播时间的间隔
	private static final int PERIOD = ServiceConstants.TIME_SERVICE_INTERVAL;

	// 最后一次执行时间
	private Date lastActionTime;

	public LocalTimeService() {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR, -1);
		this.lastActionTime = calendar.getTime();
	}

	// 获取当前时间
	public Date getTime() {
		return this.getCalendar().getTime();
	}

	// 日历
	public Calendar getCalendar() {
		return Calendar.getInstance();
	}

	// 注册时间监听者
	public void register(ITimeListener obj) {
		this.list.add(obj);
	}

	// 取消注册
	public void unregister(ITimeListener obj) {
		this.list.remove(obj);
	}

	// 启动服务
	public void startup() {
		if (this.task != null) {
			this.task.cancel();
		}
		
		if (this.timer != null) {
			this.timer.cancel();
		}

		this.timer = new Timer(false);
		this.task = new TheTimerTask();
		this.timer.schedule(this.task, 5000, PERIOD);

		this.lastActionTime = Calendar.getInstance().getTime();
	}

	// 关闭服务
	public void shutdown() {
		if (this.task != null) {
			this.task.cancel();
			this.task = null;
		}
		
		if (this.timer != null) {
			this.timer.cancel();
			this.timer = null;
		}
	}

	// 是否处于活动状态
	public boolean isAlive() {
		// return (time - this.lastActionTime) < PERIOD * 2;
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MILLISECOND, -PERIOD * 2);

		Calendar last = Calendar.getInstance();
		last.setTime(this.lastActionTime);

		return last.after(calendar);
	}

	// 服务名
	public String name() {
		return "LocalTimeService";
	}

	// 依赖哪些服务
	public Class<?>[] depends() {
		return null;
	}

	// 广播时间信息
	private void broadcast() {
		Date now = this.getTime();
		this.logger.debug("{} running", this.name());

		for (ITimeListener obj : this.list) {
			obj.setTime(now);
		}

		// 这里应该使用本地时间
		this.lastActionTime = Calendar.getInstance().getTime();
	}

	/**
	 * 定时任务对象
	 */
	private class TheTimerTask extends TimerTask {
		/**
		 * The action to be performed by this timer task.
		 */
		@Override
		public void run() {
			LocalTimeService.this.broadcast();
		}
	}
}
